<template>
  <section class="account-login">
    <h1>请先登录</h1>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="login-form">
      <el-form-item label="账户" prop="account">
        <el-input type="text" v-model="ruleForm.account" auto-complete="off"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="ruleForm.password" auto-complete="off"/>
      </el-form-item>
      <el-form-item style="text-align: left">
        <el-switch v-model="ruleForm.remember" active-text="下次自动登录">
        </el-switch>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>
<script>
import {AccountService} from '@/service/api'

export default {
  data () {
    let validateAccount = (rule, value, callback) => {
      let phone = 11 && /^((13|14|15|17|18)[0-9]{9})$/i
      let email = /^([\w-_]+(?:\.[\w-_]+)*)@((?:[a-z0-9]+(?:-[a-zA-Z0-9]+)*)+\.[a-z]{2,6})$/i
      let username = /^[\w][\w-_]{5,31}$/i
      if (phone.test(value)) {
        this.ruleForm.phone = value
      } else if (email.test(value)) {
        this.ruleForm.email = value
      } else if (username.test(value)) {
        this.ruleForm.username = value
      } else {
        callback(new Error('请输入合法账户：手机，邮箱，用户名'))
        this.resetForm()
      }
      callback()
    }
    return {
      loading: null,
      ruleForm: {
        email: '',
        phone: '',
        username: '',
        account: '',
        password: '',
        remember: false,
        captcha: ''
      },
      rules: {
        account: [
          {required: true, message: '请输入账户名称', trigger: 'change'},
          {validator: validateAccount, trigger: 'change'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'change'},
          {min: 6, max: 32, message: '长度在 6 到 32 个字符', trigger: 'change'}
        ]
      }
    }
  },
  methods: {
    resetForm: function () {
      for (let key in this.ruleForm) {
        if (key === 'account') {
          return
        }
        if (key === 'remember') {
          this.ruleForm[key] = false
        }
        this.ruleForm[key] = ''
      }
    },
    submitForm: function (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false
        }
        AccountService.login(this.ruleForm).then(
          res => {
            if (res) {
              this.$message.success('登录成功')
              if (this.$router.currentRoute.query.redirect) {
                this.$router.push({path: this.$router.currentRoute.query.redirect})
              } else {
                this.$router.push({path: '/user'})
              }
            } else {
              this.resetForm()
            }
          })
      })
    }
  }
}

</script>

<style scoped>
</style>
